package com.leyou.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * 购物车的拦截器，用于获取用户信息并保存
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final String COOKIE_NAME = "LY_TOKEN";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            //获取request中的token
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            //直接利用base64解析载荷
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            //将用户信息放入ThreadLocal中，保证并发情况下不同用户的资源不会相互影响
            UserHolder.setUser(payload.getInfo());
            return true;
        } catch (UnsupportedEncodingException e) {
            // 解析失败，不继续向下
            log.error("【购物车服务】解析用户信息失败！", e);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在视图渲染完毕后删除用户信息
        UserHolder.removeUser();
    }
}
